from flask import Flask, session, g
from flask_cors import CORS
import config
from exts import db, mail
from models import UserModel
from blueprints.auth import bp as auth_bp
from blueprints.func import bp as func_bp
from blueprints.calc import bp as calc_bp
from blueprints.sens import calc as sens_bp
from flask_migrate import Migrate

app = Flask(__name__)
CORS(app)  # 启用CORS
# 绑定配置文件
app.config.from_object(config)


db.init_app(app)
mail.init_app(app)

migrate = Migrate(app, db)

app.register_blueprint(auth_bp)
app.register_blueprint(func_bp)
app.register_blueprint(calc_bp)
app.register_blueprint(sens_bp)

# hook
# before_request:请求到达视图函数之前运行
# g是全局变量，用于存储用户信息
@app.before_request
def my_before_request():
    user_id = session.get("user_id")
    if user_id:
        user = UserModel.query.get(user_id)
        setattr(g, "user", user)
    else:
        setattr(g, "user", None)

# 上下文处理器
# 在所有模板都可是使用user对象了
@app.context_processor
def my_context_processor():
    return {"user": g.user}

if __name__ == '__main__':
    app.run()
